#-*- coding:utf-8 -*-
'''
Created on 2012-8-1

@author: johnny
'''
import db_connector

class DBQuery(object):
    def __init__(self, host, user='postgres', passwd='', db_name='fronware'):
        self.db = db_connector.DataBaseConnection()
        self.db_type = 'psql'
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db_name = db_name
        self.retry_times = 10
    
    def query(self, table, keyword, column='*'):
        if keyword: 
            command = ('SELECT ' + column + ' from ' + table +
                       ' where ' + keyword)
        else:
            command = 'SELECT ' + column + ' from ' + table
            
        command = command + ';'
        
        return self.execute(command)
    
    def execute(self, command):
        self.db.connect(self.db_type, self.host, 5432,
                               self.user, self.passwd, self.db_name)
        result = self.db.execute(command)
        self.db.disconnect()
        return result
    
    def get_storageUuid(self, keyword=None):
        column = 'uuid'
        results = self.query('storage', keyword, column)
        results = [x[0] for x in results]
        if len(results) > 1:
            return results
        else:
            return results[0]
    
    def get_storagepath(self, keyword=None):
        column = 'mount_path'
        results = self.query('storage', keyword, column)
        results = [x[0] for x in results]
        if len(results) > 1:
            return results
        else:
            return results[0]
    
    def get_hostUuid(self):
        column = 'uuid'
        results = self.query('hosts', '', column)
        results = [x[0] for x in results]
        if len(results) > 1:
            return results
        else:
            return results[0]
    
    def get_vmUuid(self, keyword=None):
        column = 'uuid'
        results = []
        times = 0       
        while not results and times < self.retry_times:
            results = self.query('vms', keyword, column)
            times += 1
        
        results = [x[0] for x in results]
        if len(results) > 1:
            return results
        else:
            return results[0]
        
    def get_vm_ip(self, vm):
        command = ("SELECT ip from vms a, netcard_vms b, " + 
                   " netcard_vms_ip c " + "where a.id=b.vm_id" + 
                   " and b.id=c.vnet_id and a.description=\'" + vm + "\';")
        
        result = self.execute(command)
        if result:
            return [x[0] for x in result][0]
        else:
            return 0
    